//
//  SuccessSetViewController.m
//  TodatPlay
//
//  Created by dllo on 16/9/20.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "SuccessSetViewController.h"
#import "OptionsTableViewCell.h"
#import "CacheTableViewCell.h"
#import "TAMacro.h"
#import "CDMNetTool.h"
#import "ExitLoginModel.h"
#import "MineViewController.h"
#import "CDMClearCache.h"
#import "SVProgressHUD.h"
#import "AppDelegate.h"
#define filePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]

#define kTableViewCellReuse @"reuse"
#define kTableViewNormalReuse @"normalReuse"
@interface SuccessSetViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *setTableView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) ExitLoginModel *exitModel;
@end

@implementation SuccessSetViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    // 使状态栏颜色为白色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    // 是的状态栏颜色为黑色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _titleArr = [NSArray array];
    [self handleData];
    [self.setTableView registerNib:[UINib nibWithNibName:@"OptionsTableViewCell" bundle:nil] forCellReuseIdentifier:kTableViewCellReuse];
     [self.setTableView registerNib:[UINib nibWithNibName:@"CacheTableViewCell" bundle:nil] forCellReuseIdentifier:kTableViewNormalReuse];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"设置";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"left_icon"] style:UIBarButtonItemStyleDone target:self action:@selector(handleLeft:)];

}
- (void)handleLeft:(UIBarButtonItem *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)handleData {
    _titleArr = @[@"清除缓存", @"意见反馈", @"检查更新", @"商务合作", @"关于今天玩什么"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return 5;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        OptionsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellReuse];
        cell.titleLabel.text = @"推送设置";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    } else {
        if (indexPath.row == 0) {
            CacheTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewNormalReuse];
            NSString *fileSize = [CDMClearCache getCacheSizeWithFilePath:filePath];
            cell.titleLabel.text = _titleArr[indexPath.row];
            if (fileSize.integerValue == 0) {
                cell.cachelabel.text = @"0M";
            } else {
                cell.cachelabel.text = fileSize;
            }

            return cell;
        } else {
            OptionsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellReuse];
            cell.titleLabel.text = _titleArr[indexPath.row];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    headView.backgroundColor = [UIColor colorWithRed:0.936 green:0.951 blue:0.982 alpha:1.000];
    return headView;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    } else {
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [backView addSubview:button];
        [button setTitle:@"退出登录" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        button.backgroundColor = [UIColor colorWithRed:1.000 green:0.000 blue:0.000 alpha:0.978];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 5;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.frame = CGRectMake(10, 20, SCREEN_WIDTH - 20, 40);
        [button addTarget:self action:@selector(handleDele:) forControlEvents:UIControlEventTouchUpInside];
        return backView;
    }
}
- (void)handleDele:(UIButton *)btn {
    NSString *httpStr = @"http://wanapi.damai.cn/user/setTokenUser.json?platform=6&channel_from=m360_market&source=10345&devid=8610540370029582&token=6448286514cd89e37503da16a15f3383&version=203004";
    
    [CDMNetTool GET:httpStr andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
        NSLog(@"退出登录成功: %@", result);
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user removeObjectForKey:@"LoginM"];
        [user removeObjectForKey:@"LoginData"];
        [user setObject:result forKey:@"exitDic"];
        [user synchronize];
        self.exitModel = [ExitLoginModel modelWithDic:result];
        if (self.exitModel.errorCode == 1) {
            AppDelegate *app = [[UIApplication sharedApplication] delegate];
            app.isLogin = NO;
            MineViewController *vc = [[MineViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    } andFailureBlock:^(NSError *error) {
        NSLog(@"退出登录失败: %@", error);
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 50;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==0&&indexPath.section==1) {
        UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"确定清除缓存吗?" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //创建一个取消和一个确定按钮
        UIAlertAction *actionCancle=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        //因为需要点击确定按钮后改变文字的值，所以需要在确定按钮这个block里面进行相应的操作
        UIAlertAction *actionOk=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            //清楚缓存
            BOOL isSuccess = [CDMClearCache clearCacheWithFilePath:filePath];
            if (isSuccess) {
                [self.setTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD showSuccessWithStatus:@"清除成功"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
            }


        }   ];
        //将取消和确定按钮添加进弹框控制器
        [alert addAction:actionCancle];
        [alert addAction:actionOk];
        //添加一个文本框到弹框控制器
        
        //显示弹框控制器
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
